package metaClass;

import java.lang.reflect.Method;

import javassist.tools.reflect.Metaobject;
import stores.StoreEnvirThread;
import fr.upmc.aladyn.transactionables.annotation.Transactionnable;


/**
 * @author 3153319 & 3003064
 *
 */
public class MyMetaobject extends Metaobject{

	private static final long serialVersionUID = -4523162520719724324L;

	public MyMetaobject(Object self, Object[] args){
		super(self, args);
	}
	
	
	
	/* (non-Javadoc)
	 * @see javassist.tools.reflect.Metaobject#trapMethodcall(int, java.lang.Object[])
	 */
	public Object trapMethodcall(int identifier, Object[] args) throws Throwable{
		
		Method myMethod = getClassMetaobject().getMethod(identifier);
				
		Object b = null;
		
		if(getMethodName(identifier).startsWith("set")){
			StoreEnvirThread.AddObjectInTheLastEnv(getObject());
		}
		
		if(myMethod.isAnnotationPresent(Transactionnable.class)){
			StoreEnvirThread.newEnv();
			StoreEnvirThread.AddObjectInTheLastEnv(getObject());
			try {
				b = super.trapMethodcall(identifier, args);
			} catch(Exception e ){
				StoreEnvirThread.RestaureAndRemoveLastEnv();
			}
			StoreEnvirThread.DeleteLastEnv();
			return b;
		} 
		return super.trapMethodcall(identifier, args);
	}

}
